package com.tenglong.teacher.ui.homepage;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.cuotibao.zhuoxiao.basics.GlobalConstant;
import com.cuotibao.zhuoxiao.basics.utils.ToastUtils;
import com.cuotibao.zhuoxiao.basics.utils.file.UriToPathUtil;
import com.cuotibao.zhuoxiao.basics.utils.glide.GlideOptions;
import com.cuotibao.zhuoxiao.basics.utils.permission.PermissionManager;
import com.tenglong.teacher.BuildConfig;
import com.tenglong.teacher.R;
import com.tenglong.teacher.data.resultInfo.StudentSignBottomInfo;
import com.tenglong.teacher.data.resultInfo.base.BaseResult;
import com.tenglong.teacher.data.resultInfo.base.ResultVerifier;
import com.tenglong.teacher.services.hdx.CreateRequestEntity;
import com.tenglong.teacher.ui.PhotoBrowserActivity;
import com.tenglong.teacher.ui.audio.AudioLayout;
import com.tenglong.teacher.ui.audio.MediaManager;
import com.tenglong.teacher.ui.audio.Recorder;
import com.tenglong.teacher.ui.common.activity.BaseActivity;
import com.tenglong.teacher.ui.dialog.ExitDialog;
import com.tenglong.teacher.ui.dialog.PictureDialogFragment;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class ClassroomRecordEvaluateActivity extends BaseActivity implements AudioLayout.AudioFinishRecorderListener {

    public static final String KEY_CLASSROOM_DATA = ClassroomRecordEvaluateActivity.class.getSimpleName() + "key_classroom_data";
    private RatingBar ratingBar;
    private EditText etEvaluate;
    private ImageView image;
    private TextView btn_audio;
    private View btn_delete_auto;
    private AudioLayout longPress;
    private RelativeLayout uploadImage;
    private Recorder mRecorder;
    private View rl_audio;
    private View complete;
    private StudentSignBottomInfo data;
    private Uri imageUri;
    private File mPhotoFile;
    private String path;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        PermissionManager.getInstances().requestPermission(1000, new String[]{android.Manifest.permission.RECORD_AUDIO}, new Runnable() {
            @Override
            public void run() {
                setContentView(R.layout.activity_classroom_record_evaluate);
                data = (StudentSignBottomInfo) getIntent().getSerializableExtra(KEY_CLASSROOM_DATA);
                initView();
                setListeners();
            }
        }, null, this);
    }

    private void setListeners() {
        longPress.setAudioFinishRecorderListener(this);
        btn_audio.setOnClickListener(this);
        btn_delete_auto.setOnClickListener(this);
        uploadImage.setOnClickListener(this);
        complete.setOnClickListener(this);
        image.setOnClickListener(this);
    }

    private void initView() {
        setTitle("课堂记录");
        ratingBar = findViewById(R.id.ratingBar);
        etEvaluate = findViewById(R.id.et_evaluate);
        image = findViewById(R.id.image);
        btn_audio = findViewById(R.id.btn_audio);
        btn_delete_auto = findViewById(R.id.btn_delete_auto);
        longPress = findViewById(R.id.longPress);
        uploadImage = findViewById(R.id.uploadImage);
        rl_audio = findViewById(R.id.rl_audio);
        complete = findViewById(R.id.complete);
        complete.setVisibility(View.VISIBLE);
    }

    @Override
    public void onFinish(float seconds, String filePath) {
        mRecorder = new Recorder(seconds, filePath);
        int sec = (int) seconds;
        btn_audio.setText(sec + "秒");
        rl_audio.setVisibility(View.VISIBLE);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case GlobalConstant.REQUEST_CODE_SHOOT:
                    image.setVisibility(imageUri == null ? View.GONE : View.VISIBLE);
                    if (imageUri == null) return;
                    Glide.with(this)
                            .load(imageUri)
                            .apply(GlideOptions.getGlideRequestOptions())
                            .into(image);
                    mPhotoFile = new File(path);
                    break;
                case GlobalConstant.REQUEST_CODE_GAINT_PHOTO:
                    if (data != null) {
                        imageUri = data.getData();
                        image.setVisibility(imageUri == null ? View.GONE : View.VISIBLE);
                        if (imageUri == null) return;
                        Glide.with(this)
                                .load(imageUri)
                                .apply(GlideOptions.getGlideRequestOptions())
                                .into(image);
                        mPhotoFile = new File(UriToPathUtil.getImageAbsolutePath(this, imageUri));
                    }
                    break;
                case GlobalConstant.REQUEST_CODE_PREVIEW:
                    finish();
                    break;
            }
        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.btn_audio:
                if (mRecorder != null) {
                    MediaManager.release();
                    MediaManager.playSound(mRecorder.getFilePath(), null);
                }
                break;
            case R.id.btn_delete_auto:
                rl_audio.setVisibility(View.GONE);
                mRecorder = null;
                break;
            case R.id.uploadImage:
                PictureDialogFragment.getInstance().setPictureDialogListener(new PictureDialogFragment.PictureDialogListener() {
                    @Override
                    public void onPhotoAlbum() {
                        photoAlbum();
                    }

                    @Override
                    public void onShoot() {
                        shoot();
                    }

                    @Override
                    public void onCancle() {
                    }
                }).show(getSupportFragmentManager(), "pictureDialogFragment");
                break;
            case R.id.complete:
                requestData();
                break;
            case R.id.image:
                if (imageUri != null && mPhotoFile != null){
                    Intent i = new Intent();
                    i.setClass(this,PhotoBrowserActivity.class);
                    i.putExtra(GlobalConstant.KEY_IMAGE_URLS,new String[]{mPhotoFile.getAbsolutePath()});
                    i.putExtra(GlobalConstant.KEY_CURRENT_IMAGE_URL,mPhotoFile.getAbsolutePath());
                    startActivity(i);
                    overridePendingTransition(0, 0);
                }
                break;
        }
    }


    private void photoAlbum() {
        Intent intent = new Intent(
                Intent.ACTION_PICK,
                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, GlobalConstant.REQUEST_CODE_GAINT_PHOTO);
    }

    private void shoot() {
        path = Environment.getExternalStorageDirectory() + "/cuoTiBao/" + System.currentTimeMillis() + ".jpg";
        File f = new File(path);
        if (!f.getParentFile().exists()) {
            f.getParentFile().mkdir();
        }
        imageUri = FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID + ".fileprovider", f);//这里进行替换uri的获得方式
        Intent intent = new Intent();
        intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        startActivityForResult(intent, GlobalConstant.REQUEST_CODE_SHOOT);
    }

    private void perView() {
        data.classShapeText = etEvaluate.getText().toString().trim();
        if (imageUri != null && mPhotoFile != null) {
            data.classShapeImg = mPhotoFile.getAbsolutePath();
        }
        if (mRecorder != null) {
            data.classShapeVideo = mRecorder.filePath;
            data.recorderDuration = ((int) mRecorder.time);
        }
        data.classPerformanceEvaluation = (int) ratingBar.getRating();
        Intent recorderIntent = new Intent(this, EvaluatePreviewActivity.class);
        recorderIntent.putExtra(EvaluatePreviewActivity.KEY_PREVIEW_DATA, data);
        recorderIntent.putExtra(EvaluatePreviewActivity.KEY_DATA_RESOURCE, EvaluatePreviewActivity.RESOURCE_CLASS_ROOM_RECORDE);
        startActivityForResult(recorderIntent, GlobalConstant.REQUEST_CODE_PREVIEW);
    }


    private void requestData() {
        MultipartBody.Part photoPart;
        if (mPhotoFile != null) {
            File photoFile = new File(mPhotoFile.getAbsolutePath());
            RequestBody photoBody =
                    RequestBody.create(MediaType.parse("multipart/form-data"), photoFile);
            photoPart = MultipartBody.Part.createFormData("classShapeImg", photoFile.getName(), photoBody);
        } else {
            photoPart = MultipartBody.Part.createFormData("", "");
        }

        MultipartBody.Part recorderPart;
        if (mRecorder != null) {
            File recorderFile = new File(mRecorder.filePath);
            RequestBody recorderBody =
                    RequestBody.create(MediaType.parse("multipart/form-data"), recorderFile);
            recorderPart = MultipartBody.Part.createFormData("classShapeVideo", recorderFile.getName(), recorderBody);
        } else {
            recorderPart = MultipartBody.Part.createFormData("", "");
        }
        showProgressDialog("数据上传中...");
        List<MultipartBody.Part> parts = new ArrayList<>();
        parts.add(photoPart);
        parts.add(recorderPart);
        int position;
        if (mRecorder == null && mPhotoFile != null) {
            position = 1;
        } else if (mRecorder == null && mPhotoFile == null) {
            position = 2;
        } else if (mRecorder != null && mPhotoFile == null) {
            position = 3;
        } else {
            position = 0;
        }
        CreateRequestEntity.getWebService().classroomEvaluate(position, parts, etEvaluate.getText().toString().trim(), (int) ratingBar.getRating(), data.classRecordId, data.id, mRecorder == null ? 0 : mRecorder.time).enqueue(new Callback<BaseResult<String>>() {
            @Override
            public void onResponse(Call<BaseResult<String>> call, Response<BaseResult<String>> response) {
                dismissProgressDialog();
                if (ResultVerifier.isSucceed(response)) {
                    setResult(Activity.RESULT_OK);
                    perView();
                } else {
                    ToastUtils.showCenterToast(ResultVerifier.serceErrers(response));
                }
            }

            @Override
            public void onFailure(Call<BaseResult<String>> call, Throwable t) {
                dismissProgressDialog();
                ResultVerifier.systerErrers(t);
            }
        });
    }

    @Override
    public void onBackPressed() {
        if ((ratingBar!=null&&ratingBar.getRating()>0)||(etEvaluate!=null&& !TextUtils.
                isEmpty(etEvaluate.getText().toString().trim()))||mRecorder!=null||(image!=null&&image.getVisibility()==View.VISIBLE)){
            ExitDialog.getExitDialog("是否放弃此次编辑？").setExitListener(new ExitDialog.ExitListener() {
                @Override
                public void onExit(boolean exitState) {
                    if (exitState) {
                        ClassroomRecordEvaluateActivity.super.onBackPressed();
                    }
                }
            }).show(getSupportFragmentManager(), "dialog");
        } else {
            super.onBackPressed();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        MediaManager.pause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        MediaManager.resume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        MediaManager.release();
    }
}
